import { getBlogList } from '@/api/blog'

const blog = {
  state: {
    blogTag: null,
    blogType: null,
    currentTag: null,
    currentType: null,
    selectOrder: 1,
    blogList: [], // 博客列表
    blogDetail: '' // 博客对象
  },
  mutations: {
    setCurrentTag: (state, nowTag) => {
      state.currentTag = nowTag
    },
    setCurrentType: (state, nowType) => {
      state.currentType = nowType
    },
    setBlogType: (state, type) => {
      if (state.blogType === null || state.blogType !== type) {
        state.blogType = type
      } else {
        state.blogType = null
      }
    },
    setBlogTag: (state, tag) => {
      if (state.blogTag === null || state.blogTag !== tag) {
        state.blogTag = tag
      } else {
        state.blogTag = null
      }
    },
    setSelectOrder: (state, order) => {
      state.selectOrder = order
    },
    // 清空博客列表
    clearBlogList: (state) => {
      state.blogList = []
    },
    // 更新博客列表内容
    renewBlogList: (state, list) => {
      state.blogList.push(...list)
    },
    setBlogDetail: (state, blogDetail) => {
      state.blogDetail = blogDetail
    },
    clearBlogDetail: (state) => {
      state.blogDetail = {}
    }
  },
  actions: {
    // 刷新博客列表
    refreshBlogs: ({ commit, state }, param) => {
      return new Promise((resolve, reject) => {
        const saveTempList = [...state.blogList]
        // 先乐观的清空博客列表
        commit('clearBlogList')
        getBlogList(param).then(res => {
          commit('renewBlogList', res.data.records)
          resolve(res)
        }).catch(error => {
          // 还原备份数据
          commit('renewBlogList', saveTempList)
          reject(error)
        })
      })
    }

  }
}

export default blog
